package org.qqcui.designpattern.patterns.adapter.springmvc;

import java.util.ArrayList;
import java.util.List;

/**
 * desc
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022/4/28 17:43
 **/
public class DispatchServlet {

    public static List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    public DispatchServlet() {
        handlerAdapters.add(new HttpHandlerAdapter());
        handlerAdapters.add(new SimpleHandlerAdapter());
        handlerAdapters.add(new AnnotationHandlerAdapter());
    }

    public void doDispatch() {
        // 模拟从请求中获取handler对象
        // SimpleController controller = new SimpleController();
        HttpController controller = new HttpController();
        // 得到对应的适配器
        HandlerAdapter ha = getHandler(controller);
        if (ha != null) {
            ha.handle(controller);
        }
    }

    /**
     * 获取具体的handler对象
     * @param controller
     * @return
     */
    private HandlerAdapter getHandler(Controller controller) {
        for (HandlerAdapter handlerAdapter : handlerAdapters) {
            boolean supports = handlerAdapter.supports(controller);
            if (supports) {
                return handlerAdapter;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        new DispatchServlet().doDispatch();
    }
}
